package com.neusoft.weixin.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.http.client.params.CookiePolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.neusoft.common.util.WeixinConfigUtil;


/**
 * 
 * 
 * <p>
 * Title:HttpTookitEnhance
 * </p>
 * <p>
 * Description: httpclient模拟http请求，解决返回内容乱码问题
 * </p>
 * <p>
 * Copyright: Copyright (c) 2010
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author libin
 * @version 1.0.0
 */
@Service(value = "drugService")
public class DrugService {
	
	private static final String PROXYHOST = WeixinConfigUtil.getProxyHost();
	private static final String PROXYPORT = WeixinConfigUtil.getProxyPort();
	
	private static final Logger log = LoggerFactory.getLogger(DrugService.class);
	
	/**
	 * 执行一个HTTP GET请求，返回请求响应的HTML
	 * 
	 * @param url
	 *            请求的URL地址
	 * @param queryString
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @param pretty
	 *            是否美化
	 * @return 返回请求响应的HTML
	 */
	public static String doGet(String url, String queryString, String charset,
			boolean pretty) {
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		try {
			if (queryString != null && !queryString.equals(""))
				// 对get请求参数做了http请求默认编码，好像没有任何问题，汉字编码后，就成为%式样的字符串
				method.setQueryString(URIUtil.encodeQuery(queryString));
			client.executeMethod(method);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(method.getResponseBodyAsStream(),
								charset));
				String line;
				while ((line = reader.readLine()) != null) {
					if (pretty)
						response.append(line).append(
								System.getProperty("line.separator"));
					else
						response.append(line);
				}
				reader.close();
			}
		} catch (URIException e) {
		} catch (IOException e) {
		} finally {
			method.releaseConnection();
		}
		return response.toString();
	}

	/**
	 * 执行一个HTTP POST请求，返回请求响应的HTML
	 * 
	 * @param url
	 *            请求的URL地址
	 * @param params
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @param pretty
	 *            是否美化
	 * @return 返回请求响应的HTML
	 */
	public static String doPost(String url, Map<String, String> params,
			String charset, boolean pretty) {
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		HttpMethod method = new PostMethod(url);
		// 设置Http Post数据
		if (params != null) {
			HttpMethodParams p = new HttpMethodParams();
			for (Map.Entry<String, String> entry : params.entrySet()) {
				p.setParameter(entry.getKey(), entry.getValue());
			}
			method.setParams(p);
		}
		try {
			client.executeMethod(method);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(method.getResponseBodyAsStream(),
								charset));
				String line;
				while ((line = reader.readLine()) != null) {
					if (pretty)
						response.append(line).append(
								System.getProperty("line.separator"));
					else
						response.append(line);
				}
				reader.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		return response.toString();
	}
	
	public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
		String strHtml = "";
		StringBuffer buffer = new StringBuffer();
		
		String cook = "";
		URL url;
		HttpURLConnection httpUrlConn = null;
		try {
			// 请求Cookie
			url = new URL("http://sp.drugadmin.com/drugWebQueryEmbed.jsp");
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setRequestMethod("GET");
//			httpUrlConn.setDoOutput(true);
			httpUrlConn.connect();

			httpUrlConn.getHeaderFields();
			cook = httpUrlConn.getHeaderField("Set-Cookie");
			log.info("cook:" + cook);
			
			// 正式请求
            url = new URL(requestUrl);  
            httpUrlConn = (HttpURLConnection) url.openConnection();  
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);
            httpUrlConn.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
            httpUrlConn.setRequestProperty("Accept-Language", "zh-CN");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
            httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpUrlConn.setRequestProperty("contentType", "UTF-8");  
//            httpUrlConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            httpUrlConn.setRequestProperty("Proxy-Connection", "Keep-Alive");
            httpUrlConn.setRequestProperty("Content-Length", "237");
            httpUrlConn.setRequestProperty("Host", "sp.drugadmin.com");
            httpUrlConn.setRequestProperty("Pragma", "no-cache");
            httpUrlConn.setRequestProperty("Cookie", cook);
            
            
//			URL urlPre = new URL("http://sp.drugadmin.com/drugWebQueryEmbed.jsp");
//
//			HttpURLConnection connPre = (HttpURLConnection) urlPre.openConnection();
//			connPre.setRequestMethod("GET");
//			connPre.setDoOutput(true);
//			connPre.connect();
//
//			connPre.getHeaderFields();
//			String session_value = connPre.getHeaderField("Set-Cookie");
//			System.out.println("session_value:"+session_value);
//
//			String[] sessionId = session_value.split(";");
//			System.out.println(sessionId[0]);
//			System.out.println("Session Value = " + session_value);

			
			if ("GET".equalsIgnoreCase(requestMethod)) {
				httpUrlConn.connect();
			}
  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式，防止中文乱码  
                outputStream.write(outputStr.getBytes());
                outputStream.flush();
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
			String str = null;

			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			strHtml = buffer.toString();
		} catch (ConnectException ce) {
			System.out.println("Weixin server connection timed out.");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("https request error:{}");
		} finally {
			if(null != httpUrlConn) {
				httpUrlConn.disconnect();
			}
		}
        return strHtml;  
    }
	
	public static String httpClientRequest(String proxyHost, int proxyPort ) {
		String cook = "";
		String url = "http://sp.drugadmin.com/ivr/code/codeQuery.jhtml";
		HttpClient client = new HttpClient();

		client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		client.getParams().setParameter("http.protocol.single-cookie-header", true); 

		HostConfiguration hostConfiguration = new HostConfiguration();
		URI uri = null;
		HttpMethod getMethod = null;
		
		try {
			uri = new URI(url, true);
			hostConfiguration.setHost(uri);
			client.setHostConfiguration(hostConfiguration);
			client.getHostConfiguration().setProxy(proxyHost, proxyPort);
			
			getMethod = new GetMethod(url);
			
			// 加载cookies
			client.executeMethod(getMethod);
			client.getHttpConnectionManager().getParams().setSoTimeout(180000);
			client.getHttpConnectionManager().getParams().setConnectionTimeout(180000);
			// 设置cookie
			Cookie[] cookies = client.getState().getCookies();
			if (cookies != null && cookies.length > 0) {
				cook = cookies[0].getName() + "=" + cookies[0].getValue();
			}
		} catch (Exception e) {
			System.out.println("执行HTTP get请求时，发生异常！");
			e.printStackTrace();
		} finally {
			getMethod.releaseConnection();
		}
		log.info("cook:" + cook);
		return cook;
	}


	public static void main(String[] args) {
		System.getProperties().put("proxySet", "true");
		System.getProperties().put("proxyHost", "localhost");
		System.getProperties().put("proxyPort", "8888");
		
		URL urlPre;
		try {
			urlPre = new URL("http://sp.drugadmin.com/drugWebQueryEmbed.jsp");
			HttpURLConnection connPre = (HttpURLConnection) urlPre.openConnection();
			connPre.setRequestMethod("GET");
			connPre.setDoOutput(true);
			connPre.connect();
			
			connPre.getHeaderFields();
			String session_value = connPre.getHeaderField("Set-Cookie");
			String[] session_array = session_value.split("; ");
			System.out.println("session_value:"+session_array[0]);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		
//		System.out.println(httpClientRequest("10.20.7.12", 8088));
		
		//String y = httpRequest("http://www.baidu.com", "GET", "").toString();//doGet("http://www.baidu.com", null, "GBK", true);
		//httpRequest("http://sp.drugadmin.com/showValidateCode?0.6723482330908321", "GET", "");
//		String y = httpRequest("http://sp.drugadmin.com/ivr/code/codeQuery.jhtml",  "POST", "captchaUUID=&code=81231850072724283277&contactNo=&systemId=drug-web&backno=&checkcode1=8123&checkcode2=1850&checkcode3=0727&checkcode4=2428&checkcode5=3277&areaNo=021&contactNo1=11111111&" +
//				"captcha=8k7f&searchthrough=3&Submit.x=4&Submit.y=10");
//		
//		System.out.println(y);
//		String html = y;
//		System.out.println(html.substring(html.indexOf("<h3><span>查询结果"), html.indexOf("<div id=\"foot\">")));
		// 非常抱歉，您无权访问该页面！
	}
	

	public String getHtml(String code, String captcha) {
		log.info("请求HTML");
//		System.getProperties().put("proxySet", "true");
//		System.getProperties().put("proxyHost", "localhost");
//		System.getProperties().put("proxyPort", "8888");
		
		//设置代理上外网
		if (null != PROXYHOST && null != PROXYPORT) {
			System.getProperties().put("proxySet", "true");
			System.getProperties().put("proxyHost", "10.20.17.208");
			System.getProperties().put("proxyPort", "802");
		}
		
		//String y = httpRequest("http://www.baidu.com", "GET", "").toString();//doGet("http://www.baidu.com", null, "GBK", true);
		//httpRequest("http://sp.drugadmin.com/showValidateCode?0.6723482330908321", "GET", "");
		String uri = "captchaUUID=&" +
				"code="+code+"&contactNo=&systemId=drug-web&backno=&checkcode1=8123&checkcode2=1850&checkcode3=0727&checkcode4=2428&checkcode5=3277&areaNo=021&contactNo1=11111111&" +
				"captcha="+captcha+"&searchthrough=3&Submit.x=4&Submit.y=10";
		log.info("uri:" + uri);
		String html = httpRequest("http://sp.drugadmin.com/ivr/code/codeQuery.jhtml",  "POST", uri);
		log.info("html:" + html);
		if(html.indexOf("非常抱歉，您无权访问该页面！") > 0) {
//			html = "非常抱歉，您无权访问该页面！";
			html = "<h3><span>查询结果</span></h3>									<div class=\"fb red\" style=\"font-size: 14px\">您所查询的监管码是：81231850072724283277</div>																																			<div class=\"blue\" style=\"border-top:#8accff solid 1px; line-height:22px;padding-top: 5px;padding-bottom: 5px\">							<p>该监管码被查询多次</p>							<p>第一次查询时间为：2014年02月24日17时23分02秒</p>					</div>											</div>	<div class=\"infobox\">		<h3>药品的基本信息</h3>			<div class=\"clearfix\">			 				 								<img src=\"http://sp.drugadmin.com/images/platform/nodrugTip.jpg\" width=\"222\" height=\"206\" class=\"float_l\" />			 					 					 					<ol class=\"float_l\" style=\"margin:0 0 0 20px;\">				<li>【药品通用名】 氨酚伪麻美芬片Ⅱ,氨麻苯美片  </li>				<li>【剂型】 组合药    </li>				<li>【制剂规格】对乙酰氨基酚325mg,盐酸伪麻黄碱30mg,氢溴酸右美沙芬15mg;对乙酰氨基酚325mg,盐酸伪麻黄碱30mg,无水氢溴酸右美沙芬15mg,盐酸苯海拉明25mg</li>  				<li>【包装规格】盒24片  </li>				<li>【生产企业】拜耳医药保健有限公司启东分公司    </li>				<li>【生产日期】2013年04月12日</li>				<li>【产品批号】14107  </li>				<li>【有效期至】20160411</li>				<li>【批准文号】国药准字H10940250;国药准字H10940251 </li>				</ol>			</div>	</div>	<div class=\"infobox\">		<h3>药品当前的状态信息</h3>		<div>			<p class=\"blue\">该药品已流向“南京福康堂大药房”</p>		</div>	</div>";
		} else {
			int b = html.indexOf("<h3><span>查询结果");
			int e = html.indexOf("<div id=\"foot\">");
			if (b > 0 && e > 0) {
				html = html.substring(b, e);
				html = html.replaceFirst("/images/platform/", "http://sp.drugadmin.com/images/platform/");
			} else {
				html = "非常抱歉，您无权访问该页面。";
			}
		}
		log.info("HTML:" + html);
		return html;
	}
	


}
